/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.modules.search;

import org.apache.commons.lang.StringUtils;

import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Model;
import com.koorz.modules.crawl.CrawlHistory;
import com.koorz.modules.image.Image;
import com.koorz.modules.user.User;



/**
 * 功能描述：下载图片任务
 * 作        者：尹东东 
 * 创建时间：2013-5-27 下午3:58:46
 * 版  本  号：1.0
 */
public class ImageTask implements Runnable{
	protected final Logger logger = Logger.getLogger(getClass());
	
	private IParser parser;
	
	public ImageTask(IParser parser){
		this.parser = parser;
	}
	
	@Override
	public void run() {
		while (true) {
			if(parser.isStopCrawl() && ThreadPoolMananger.ImageQueue.isEmpty()){
				logger.debug("抓取图片完成。");
				break;
			}
			Model item = null;
			try {
				item = ThreadPoolMananger.ImageQueue.take();
				parser.getQueue();
			} catch (InterruptedException e) {
				e.printStackTrace();
				logger.error("ImageTask 添加单品搭配队列停止标识失败！", e);
				break;
			}
			SimpleHttpClient client = new SimpleHttpClient();
			TaskService taskService = TaskService.getInstance();
			String url = "";
			try {
				if(item instanceof User){
					User user = (User) item;
					url = user.getStr("avatar_large");
					taskService.compressAvatar(client, user);
				}else if(item instanceof Image){
					Image image = (Image) item;
					url = image.getStr("url");
					taskService.compressImage(client, image);
				}
				String host = StringUtils.substringBetween(url, "http://", "/");
				CrawlHistory crawlH = new CrawlHistory();
				crawlH.set("website", host);
				crawlH.set("url", url);
				taskService.addCrawlHistory(crawlH);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("保存图片失败 compressImage,url:" + url, e);
			}
			client.close();
		}
	}
}
